import 'package:flutter/material.dart';
import 'package:flutter_pickers/pickers.dart';
import 'package:flutter_pickers/time_picker/model/date_mode.dart';
import 'package:flutter_pickers/time_picker/model/pduration.dart';
import 'package:get/get.dart';
import 'package:ty_smart_watch/ble/ble_util.dart';
import 'package:ty_smart_watch/ble/protocol_data_util.dart';
import 'package:ty_smart_watch/page/watch_setting_page/controller/watch_setting_controller.dart';
import 'package:ty_smart_watch/utils/Log.dart';

class WatchDoNotDisturbPage extends StatefulWidget {
  const WatchDoNotDisturbPage({super.key});

  @override
  State<WatchDoNotDisturbPage> createState() => _WatchDoNotDisturbPageState();
}

class _WatchDoNotDisturbPageState extends State<WatchDoNotDisturbPage> {
  int _functionId = 0; //功能id
  String _mac = ""; //设备地址

  final _trailingStyle = const TextStyle(color: Color(0xFF3075E9));
  final _titleStyle = const TextStyle(fontSize: 18);
  final _confirmColor = const Color(0xFF3075E9);
  final _unConfirmColor = const Color(0xFF80A3DF);

  final _controller = Get.put(WatchSettingController());

  @override
  void initState() {
    super.initState();
    _functionId = Get.arguments["id"];
    _mac = Get.arguments["mac"];
    Log.d("页面收到的数据：$_functionId > $_mac");
    _controller.getBleData(_mac, _functionId);
  }

  @override
  Widget build(BuildContext context) {
    ever(
      _controller.needClosePage,
      (need) => {
        Log.d("need close page: $need"),
        if (need == 2) {Get.back()}
      },
    );
    return Scaffold(
      appBar: AppBar(
        title: const Text("勿扰模式"),
        centerTitle: true,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios),
          onPressed: () {
            Get.back();
          },
        ),
      ),
      body: Column(
        children: [
          //开关
          Obx(
            () => SwitchListTile(
              dense: true,
              inactiveThumbColor: _unConfirmColor,
              inactiveTrackColor: _unConfirmColor.withAlpha(88),
              activeColor: _confirmColor,
              activeTrackColor: _confirmColor.withAlpha(88),
              title: Text("开关", style: _titleStyle),
              onChanged: (bool value) {
                Log.d("switch value :  $value");
                var temp = _controller.doNotDisturbBean.value;
                Log.d("timeRangeBean switch  value :  ${temp.isSwitch}");
                if (!value) {
                  temp.isSwitch = 0;
                } else {
                  temp.isSwitch = 2;
                }
                _controller.updateDoNotDisturbBean(temp);
              },
              value: _controller.doNotDisturbBean.value.isSwitch != 0,
            ),
          ),
          //todo RadioGroup

          Obx(
            () => Visibility(
              visible: _controller.doNotDisturbBean.value.isSwitch != 0,
              child: Column(
                children: [
                  //全天/自定义时段按钮
                  Row(
                    children: [
                      const Expanded(child: SizedBox()),
                      Radio(
                        value: 1,
                        activeColor: _confirmColor,
                        visualDensity: const VisualDensity(vertical: -4, horizontal: -4),
                        groupValue: _controller.doNotDisturbBean.value.isSwitch,
                        onChanged: (data) {
                          var temp = _controller.doNotDisturbBean.value;
                          temp.isSwitch = data ?? 2;
                          _controller.updateDoNotDisturbBean(temp);
                        },
                        materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                      ),
                      const Text(
                        '自定义时段',
                        style: TextStyle(fontSize: 14),
                      ),
                      Radio(
                        value: 2,
                        activeColor: _confirmColor,
                        visualDensity: const VisualDensity(vertical: -4, horizontal: -4),
                        groupValue: _controller.doNotDisturbBean.value.isSwitch,
                        onChanged: (data) {
                          setState(() {
                            var temp = _controller.doNotDisturbBean.value;
                            temp.isSwitch = data ?? 2;
                            _controller.updateDoNotDisturbBean(temp);
                          });
                        },
                      ),
                      const Text(
                        '全天',
                        style: TextStyle(fontSize: 14),
                      ),
                      const SizedBox(width: 20),
                    ],
                  ),
                  Visibility(
                      visible: _controller.doNotDisturbBean.value.isSwitch == 1,
                      child: Column(
                        children: [
                          //开始时间
                          ListTile(
                            title: Text("开始时间", style: _titleStyle),
                            trailing: Obx(
                              () => Text(
                                "${_controller.doNotDisturbBean.value.startHour}:${_controller.doNotDisturbBean.value.startMinute}",
                                style: _trailingStyle,
                              ),
                            ),
                            onTap: () {
                              _clickStartTime(_controller.doNotDisturbBean.value.startHour,
                                  _controller.doNotDisturbBean.value.startMinute);
                            },
                          ),

                          //结束时间
                          ListTile(
                            title: Text("结束时间", style: _titleStyle),
                            trailing: Obx(
                              () => Text(
                                "${_controller.doNotDisturbBean.value.endHour}:${_controller.doNotDisturbBean.value.endMinute}",
                                style: _trailingStyle,
                              ),
                            ),
                            onTap: () {
                              _clickEndTime(_controller.doNotDisturbBean.value.endHour,
                                  _controller.doNotDisturbBean.value.endMinute);
                            },
                          ),
                        ],
                      ))
                ],
              ),
            ),
          ),

          //占位
          const Expanded(child: SizedBox()),
          //确认按钮
          Container(
            width: double.infinity,
            height: 46,
            margin: const EdgeInsets.symmetric(horizontal: 20),
            child: TextButton(
              onPressed: () {
                _confirm();
              },
              style: ButtonStyle(
                backgroundColor: MaterialStateProperty.all(Colors.blue),
                foregroundColor: MaterialStateProperty.all(Colors.white),
                shape: MaterialStateProperty.all(
                  const RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(Radius.circular(30)),
                  ),
                ),
              ),
              child: const Text('确认'),
            ),
          ),
          const SizedBox(height: 60),
        ],
      ),
    );
  }

  _clickStartTime(int hour, int minute) {
    Pickers.showDatePicker(
      context,
      mode: DateMode.HM,
      selectDate: PDuration(hour: hour, minute: minute),
      onConfirm: (p) {
        Log.d('开始时间选择器：$p');
        var temp = _controller.doNotDisturbBean.value;
        temp.startHour = p.hour ?? 0;
        temp.startMinute = p.minute ?? 0;
        _controller.updateDoNotDisturbBean(temp);
      },
    );
  }

  _clickEndTime(int hour, int minute) {
    Pickers.showDatePicker(
      context,
      mode: DateMode.HM,
      selectDate: PDuration(hour: hour, minute: minute),
      onConfirm: (p) {
        Log.d('结束时间选择器：$p');
        var temp = _controller.doNotDisturbBean.value;
        temp.endHour = p.hour ?? 0;
        temp.endMinute = p.minute ?? 0;
        _controller.updateDoNotDisturbBean(temp);
      },
    );
  }

  /// 提交信息到手表
  _confirm() {
    //将数据传送给手表 write
    _controller.updateNeedClosePage(1);
    var mData = _makeDataForWatch();
    BleUtil.writeBleData(_mac, BleUtil.makeWriteData(functionId: _functionId, data: mData));
  }

  ///整合要提交的数据
  List<int> _makeDataForWatch() {
    var temp = _controller.doNotDisturbBean.value;
    List<int> result = ProtocolDataUtil.instance!.doNotDisturb(
        temp.isSwitch, temp.startHour, temp.startMinute, temp.endHour, temp.endMinute);
    return result;
  }
}
